﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBMode
{
    public class CommodityMethod:IMethods<Commodity>
    {
        public int Add(Commodity t)
        {
            using (CMSDBEntities cMSDB = new CMSDBEntities())
            {
                if (t == null) return 0;
                t.CreateTime = DateTime.Now;
                cMSDB.Commodity.Add(t);
                int a = cMSDB.SaveChanges();
                return a;
            }
        }

        public int Delete(Commodity t)
        {
            using (CMSDBEntities cMSDB = new CMSDBEntities())
            {
                int a = 0;
                var model = cMSDB.Commodity.ToList().FirstOrDefault(i=>i.Name==t.Name);
                if (model != null) {
                    cMSDB.Commodity.Remove(model);
                    a = cMSDB.SaveChanges();
                        }
                return a;
            }
        }

        public List<Commodity> Query()
        {
            using (CMSDBEntities cMSDB = new CMSDBEntities())
            {
                return cMSDB.Commodity.ToList();
            }
        }

        public int Update(Commodity t)
        {
            using (CMSDBEntities cMSDB = new CMSDBEntities())
            {
                int a = 0;
                if (t == null) return 0;
                var model = cMSDB.Commodity.ToList().FirstOrDefault(i => i.Id == t.Id);
                if (model != null)
                {
                    model.Name = t.Name;
                    model.Type = t.Type;
                    model.Unit = t.Unit;
                    model.Tag = t.Tag;
                    model.Price = t.Price;

                    a = cMSDB.SaveChanges();
                    return a;
                }
                return a;
            }
        }
    }
}
